let util = require('../../utils/util');

let requestDomain = util.config('requestDomain');

let that;

Page({

  data: {
    bankCardRealName: '',
    bankCardNumber: '',
    submitBtnDisabled: false,
    bankCardInfo: {
        bankCardRealName: '',
        bankCardNumber: ''
    }
  },

  onLoad: function () {
    that = this;
    let {storeData} = util.globalData('loginData');
    let {storeBankCardInfo} = storeData;
    if (storeBankCardInfo.bankCardRealName && storeBankCardInfo.bankCardNumber) {
        that.setData({ bankCardInfo: storeBankCardInfo });
    }
  },

  bankCardRealNameInput: function(e) {
      that.data.bankCardRealName = e.detail.value;
  },

  bankCardNumberInput: function(e) {
      that.data.bankCardNumber = e.detail.value;
  },

  submitBankCardInfoClick: function() {
    let {bankCardRealName, bankCardNumber} = that.data;
    that.setData({ submitBtnDisabled: true });
    if (bankCardRealName.length == 0) {
        wx.showModal({
            title: '提示',
            content: '请填写姓名',
            showCancel: false
        });
        that.setData({ submitBtnDisabled: false });
        return;
    }
    if (that.checkBankCardNumber(bankCardNumber)) {
        that.submitBankCardInfo(bankCardRealName, bankCardNumber);
    }
    else {
        wx.showModal({
            title: '检查卡号',
            content: '您的卡号有误，如果您确定您的银行卡号输入正确请点击智能识别来确定银行卡号有效性，请检查后再试',
            cancelText: '智能识别',
            cancelColor: '#f06759',
            success: function(modal) {
                if (!modal.confirm) {
                    that.reCheckBankCardNumber(bankCardNumber, {
                        success: function() {
                            that.submitBankCardInfo(bankCardRealName, bankCardNumber);
                        },
                        fail: function() {
                            that.setData({ submitBtnDisabled: false });
                        }
                    });
                }
                else {
                    that.setData({ submitBtnDisabled: false });
                }
            }
        });
    }
  },

  submitBankCardInfo: function (bankCardRealName, bankCardNumber) {
      wx.showModal({
          title: '确认设置？',
          content: '您的姓名为' + bankCardRealName + '，卡号为' + bankCardNumber + '，请务必确认卡号是否正确，这将关系到您的收入能否正确提现到您的账户，是否确认您的姓名与卡号正确？',
          success: function (modal) {
              if (modal.confirm) {
                  wx.showNavigationBarLoading();
                  wx.showToast({
                      title: '设置中',
                      icon: 'loading',
                      duration: 10000,
                      mask: true
                  });
                  wx.request({
                      url: requestDomain + 'store/setBankCardInfo',
                      method: 'POST',
                      data: {
                          storeId: util.globalData('storeId'),
                          _3rdSession: util.globalData('_3rdSession'),
                          bankCardRealName: bankCardRealName,
                          bankCardNumber: bankCardNumber
                      },
                      success: function(result) {
                          wx.hideNavigationBarLoading();
                          wx.hideToast();
                          if(util.checkSuccess(result) && result.data && result.data.data) {
                              let {storeData} = util.globalData('loginData');
                              storeData.storeBankCardInfo = {
                                  bankCardRealName: bankCardRealName,
                                  bankCardNumber: bankCardNumber
                              };
                              util.globalData('storeData', storeData);
                              wx.showToast({
                                  title: '设置成功',
                                  icon: 'success'
                              });
                              setTimeout(function() {
                                wx.navigateBack();
                              }, 500);
                          }
                          else {
                              that.setData({ submitBtnDisabled: false });
                              util.showError('提交失败', '提交您的设置提现银行卡失败' + result.data.errMsg, result.data.errCode);
                          }
                      },
                      fail: function() {
                          that.setData({ submitBtnDisabled: false });
                          wx.hideNavigationBarLoading();
                          wx.hideToast();
                          util.showError('提交失败', '提交您的设置提现银行卡请求失败');
                      }
                  })
              }
              else {
                  that.setData({ submitBtnDisabled: false });
              }
          }
      });
  },

  checkBankCardNumber: function(bankCardNumber) {
    if (bankCardNumber.length == 0) {
        return false;
    }
    let num1 = 0, num2 = 0, temp;
    for(let i = bankCardNumber.length - 1;i >= 0;i--) {
        if((i + 1) % 2 == 0) {
            temp = bankCardNumber[i] * 2;
            num1 += parseInt(temp > 9 ? temp - 9 : temp);
        }
        else {
            num2 += parseInt(bankCardNumber[i]);
        }
    }
    return (num1 + num2) % 10 == 0;
  },

  reCheckBankCardNumber: function (bankCardNumber, callback) {
    wx.showToast({
        title: '智能识别中',
        icon: 'loading',
        duration: 10000,
        mask: true
    });
    wx.request({
        url: 'https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=' + bankCardNumber + '&cardBinCheck=true',
        method: 'GET',
        success: function(result) {
            console.log(result.data.validated);
            wx.hideToast();
            if (result.data && result.data.validated) {
                wx.showToast({
                    title: '识别成功'
                });
                callback.success();
            }
            else {
                wx.showModal({
                    title: '卡号有误',
                    content: '通过智能识别您的卡号依然不正确，请再次检查卡号是否正确，如仍有问题请在【店铺设置>意见反馈】向我们反馈您的卡号以及问题'
                })
                callback.fail();
            }
        },
        fail: function() {
            that.setData({ submitBtnDisabled: false });
            wx.hideToast();
            util.showError('识别失败', '智能识别银行卡有效性失败，请重试');
            callback.fail();
        }
    });
  }
});